package com.dianxin.smartpark.service.common.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.constant.ErrMsgEnum;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.Convert;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.chinatelecom.response.utils.StringUtils;
import com.dianxin.acl.api.acl.AclDeptDicRpcService;
import com.dianxin.acl.api.acl.AclFileRpcService;
import com.dianxin.acl.api.acl.AclUserRpcService;
import com.dianxin.acl.api.dto.AclDeptDicDTO;
import com.dianxin.acl.api.dto.SsoUserDTO;
import com.dianxin.acl.api.dto.SsoUserDeptDTO;
import com.dianxin.acl.api.dto.SysFileDTO;
import com.dianxin.acl.api.qo.AclDeptDicQO;
import com.dianxin.acl.api.qo.SsoDeptRpcQO;
import com.dianxin.acl.api.qo.SsoUserRpcQO;
import com.dianxin.acl.api.qo.SysFileQO;
import com.dianxin.common.oss.properties.FileUploadResponse;
import com.dianxin.common.oss.util.MinioUtil;
import com.dianxin.device.api.device.SmartDeviceUserRpcService;
import com.dianxin.device.api.device.SmartParkDeviceRpcService;
import com.dianxin.device.api.device.dto.SmartDeviceDTO;
import com.dianxin.device.api.device.qo.SmartDeviceRpcQO;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkCard;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkCardExample;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkUserConfig;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkUserConfigExample;
import com.dianxin.smartpark.dao.dataobject.park.SmartParkCar;
import com.dianxin.smartpark.dao.dataobject.park.SmartParkCarExample;
import com.dianxin.smartpark.dao.dataobject.visitor.SmartParkStrategyConfig;
import com.dianxin.smartpark.dao.dataobject.visitor.SmartParkStrategyConfigExample;
import com.dianxin.smartpark.dao.dataobject.visitor.SmartParkVisitor;
import com.dianxin.smartpark.dao.dataobject.visitor.SmartParkVisitorExample;
import com.dianxin.smartpark.dao.mapper.common.SmartParkCardMapper;
import com.dianxin.smartpark.dao.mapper.common.SmartParkUserConfigMapper;
import com.dianxin.smartpark.dao.mapper.park.SmartParkCarMapper;
import com.dianxin.smartpark.dao.mapper.visitor.SmartParkStrategyConfigMapper;
import com.dianxin.smartpark.dao.mapper.visitor.SmartParkVisitorMapper;
import com.dianxin.smartpark.dao.qo.common.SmartParkUserConfigQO;
import com.dianxin.smartpark.service.common.SmartParkDeviceAuthService;
import com.dianxin.smartpark.service.common.SmartParkUserConfigService;
import com.dianxin.smartpark.service.config.MqttOptType;
import com.dianxin.smartpark.service.face.FaceEngineService;
import com.dianxin.smartpark.service.vo.common.*;
import com.dianxin.smartpark.service.vo.park.SmartParkUserCarVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户凭证业务层处理
 * 
 * @author chenjiasong
 * @date 2021-08-10
 */
@Service
public class SmartParkUserConfigServiceImpl implements SmartParkUserConfigService
{
    private final static Logger logger = LoggerFactory.getLogger(SmartParkUserConfigServiceImpl.class);
    @Resource
    private SmartParkUserConfigMapper smartParkUserConfigMapper;

    @Resource
    private SmartParkVisitorMapper smartParkVisitorMapper;

    @Resource
    private SmartParkDeviceRpcService smartParkDeviceRpcService;

    @Resource
    private SmartParkCardMapper smartParkCardMapper;

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private AclFileRpcService aclFileRpcService;

    @Resource
    private FaceEngineService faceEngineService;

    @Resource
    private SmartParkDeviceAuthService smartParkDeviceAuthService;

    @Resource
    private SmartParkStrategyConfigMapper smartParkStrategyConfigMapper;

    /**
     * 查询用户凭证
     * 
     * @param qo 用户凭证
     * @return 用户凭证
     */
    @Override
    public CommonResponseBody<SmartParkUserConfigVO> selectSmartParkUserConfig(SmartParkUserConfigQO qo)
    {
        if(StringUtils.isNull(qo.getId()) && StringUtils.isNull(qo.getUserId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
        SmartParkUserConfigExample.Criteria criteria = smartParkUserConfigExample.createCriteria();
        if (qo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        criteria.andIsDeletedEqualTo(0);
        if(StringUtils.isNotNull(qo.getId())){
            criteria.andIdEqualTo(qo.getId());
        }
        if(StringUtils.isNotNull(qo.getUserId())){
            criteria.andUserIdEqualTo(qo.getUserId());
        }
        List<SmartParkUserConfig> passRecords = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
        return ResponseBodyWrapperUtil.successWrapper(StringUtils.isNotEmpty(passRecords)?passRecords.get(0):null,SmartParkUserConfigVO.class);
    }


    /**
     * 查询用户凭证列表
     *
     * @param vo 用户凭证
     * @return 用户凭证
     */
    @Override
    public CommonResponseBody<List<SmartParkUserTzVO>> selectUserDetailList(DevicePullDataVo vo) throws Exception {
        String deviceCode = vo.getDeviceCode();
        if(StringUtils.isEmpty(deviceCode)){
            return ResponseBodyWrapperUtil.fail("设备code为空","400");
        }
        List<SmartParkUserTzVO> result = new ArrayList<>();
        List<String> userIds = smartParkDeviceAuthService.getUserIdByDeviceCode(deviceCode,vo.getOrgCode(),vo.getTenantId());
        //查询员工凭证
        SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
        SmartParkUserConfigExample.Criteria criteria1 = smartParkUserConfigExample.createCriteria();
        criteria1.andIsDeletedEqualTo(0);
        criteria1.andAccessStartDateLessThanOrEqualTo(new Date());
        criteria1.andAccessEndDateGreaterThanOrEqualTo(new Date());
        criteria1.andCharacteristicIsNotNull();
        criteria1.andTenantIdEqualTo(vo.getTenantId());
        List<SmartParkUserConfig> passRecords1 = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
        if (StringUtils.isEmpty(passRecords1)) {
            return ResponseBodyWrapperUtil.fail("无凭证数据","400");
        }
        if (userIds != null) {
            for (String userId : userIds) {
                SmartParkUserTzVO smartParkUserTzVO = new SmartParkUserTzVO();
                SmartParkUserConfig smartParkUserConfig = null;
                for(SmartParkUserConfig smartParkUserConfig1 :passRecords1){
                    if(smartParkUserConfig1.getUserId().equals(userId)){
                        smartParkUserConfig = smartParkUserConfig1;
                        break;
                    }
                }

                if (StringUtils.isNull(smartParkUserConfig)) {
                    continue;
                }
                if (StringUtils.isEmpty(smartParkUserConfig.getCharacteristic())) {
                    continue;
                }
                if (smartParkUserConfig.getBeAuthorization() == 0) {
                    continue;
                }
                smartParkUserTzVO.setUserId(Convert.toLong(smartParkUserConfig.getUserId()));
                smartParkUserTzVO.setUserType(1);
                smartParkUserTzVO.setPhoneNum(smartParkUserConfig.getPhoneNum());
                smartParkUserTzVO.setCharacteristic(smartParkUserConfig.getCharacteristic());
                smartParkUserTzVO.setUserName(smartParkUserConfig.getName());
                if (smartParkUserConfig.getAccessDateType() != null && smartParkUserConfig.getAccessDateType() == 1) {
                    smartParkUserTzVO.setAccessStartDate(smartParkUserConfig.getAccessStartDate());
                    smartParkUserTzVO.setAccessEndDate(smartParkUserConfig.getAccessEndDate());
                }

                if(StringUtils.isNotNull(smartParkUserConfig.getIsLeader()) && smartParkUserConfig.getIsLeader()==1){
                    smartParkUserTzVO.setSort(Long.MAX_VALUE);
                }else {
                    smartParkUserTzVO.setSort(0);
                }
                smartParkUserTzVO.setGmtModified(smartParkUserConfig.getGmtModified() == null ? smartParkUserConfig.getGmtCreate() : smartParkUserConfig.getGmtModified());
                smartParkUserTzVO.setIdPhoto(smartParkUserConfig.getPhoto());
                result.add(smartParkUserTzVO);
            }
        }
        //查询员工，装载数据
        //查询访客
        //查询设备区域
        SmartDeviceRpcQO smartDeviceRpcQO = new SmartDeviceRpcQO();
        smartDeviceRpcQO.setTenantId(vo.getTenantId());
        smartDeviceRpcQO.setOrgCode(Convert.toStr(vo.getOrgCode()));
        smartDeviceRpcQO.setDeviceCode(vo.getDeviceCode());
        smartDeviceRpcQO.setNeedPage(false);
        CommonResponseBody<List<SmartDeviceDTO>> smartParkDeviceRpcServiceDevices = smartParkDeviceRpcService.getDevices(smartDeviceRpcQO);
        if(!smartParkDeviceRpcServiceDevices.isSuccess() || StringUtils.isEmpty(smartParkDeviceRpcServiceDevices.getData())){
            return ResponseBodyWrapperUtil.successWrapper(result);
        }
        SmartDeviceDTO smartDeviceDTO = smartParkDeviceRpcServiceDevices.getData().get(0);
        //查访客配置
        SmartParkStrategyConfigExample smartParkStrategyConfigExample = new SmartParkStrategyConfigExample();
        SmartParkStrategyConfigExample.Criteria criteria = smartParkStrategyConfigExample.createCriteria();
        criteria.andTenantIdEqualTo(smartDeviceDTO.getTenantId());
        List<SmartParkStrategyConfig> strategyConfigs = smartParkStrategyConfigMapper.selectByExample(smartParkStrategyConfigExample);
        if(StringUtils.isEmpty(strategyConfigs)){
            return ResponseBodyWrapperUtil.successWrapper(result);
        }
        //判断权限区域
        SmartParkStrategyConfig strategyConfig = strategyConfigs.get(0);
        if(StringUtils.isEmpty(strategyConfig.getDeviceCodes())){
            return ResponseBodyWrapperUtil.successWrapper(result);
        }
        if(!strategyConfig.getDeviceCodes().contains(smartDeviceDTO.getDeviceAreaCode())){
            return ResponseBodyWrapperUtil.successWrapper(result);
        }
        //查访客
        SmartParkVisitorExample smartParkVisitorExample = new SmartParkVisitorExample();
        SmartParkVisitorExample.Criteria smartParkVisitorExampleCriteria = smartParkVisitorExample.createCriteria();
        smartParkVisitorExampleCriteria.andIsDeletedEqualTo(0);
        smartParkVisitorExampleCriteria.andTenantIdEqualTo(smartDeviceDTO.getTenantId());
        smartParkVisitorExampleCriteria.andAccessStartDateLessThanOrEqualTo(new Date());
        smartParkVisitorExampleCriteria.andAccessEndDateGreaterThanOrEqualTo(new Date());
        List<SmartParkVisitor> passRecords = smartParkVisitorMapper.selectByExample(smartParkVisitorExample);
        if(StringUtils.isEmpty(passRecords) || StringUtils.isEmpty(passRecords)){
            return ResponseBodyWrapperUtil.successWrapper(result);
        }
        for (SmartParkVisitor visitor:passRecords) {
            if (visitor.getBeAuthorization() == 0) {
                continue;
            }
            if (visitor.getOpenType() != 0) {
                continue;
            }
            if(StringUtils.isEmpty(visitor.getCharacteristic())){
                continue;
            }
            SmartParkUserTzVO smartParkUserTzVO = new SmartParkUserTzVO();
            smartParkUserTzVO.setUserId(Convert.toLong(visitor.getId()));
            smartParkUserTzVO.setUserType(2);
            smartParkUserTzVO.setPhoneNum(visitor.getVisitorPhoneNum());
            smartParkUserTzVO.setUserName(visitor.getVisitorName());
            smartParkUserTzVO.setCharacteristic(visitor.getCharacteristic());
            if (visitor.getAccessDateType() == 1) {
                smartParkUserTzVO.setAccessStartDate(visitor.getAccessStartDate());
                smartParkUserTzVO.setAccessEndDate(visitor.getAccessEndDate());
            }
            smartParkUserTzVO.setGmtModified(visitor.getGmtModified() == null ? visitor.getGmtCreate() : visitor.getGmtModified());
            result.add(smartParkUserTzVO);
        }
        return ResponseBodyWrapperUtil.successWrapper(result);
    }


    /**
     * 查询用户凭证列表
     *
     * @param vo 用户凭证
     * @return 用户凭证
     */
    @Override
    public CommonResponseBody<List<SmartParkUserCardVO>> selectUserCardDetailList(DevicePullDataVo vo) throws Exception {
        String deviceCode = vo.getDeviceCode();
        if(StringUtils.isEmpty(deviceCode)){
            return ResponseBodyWrapperUtil.fail("设备code为空","400");
        }
        List<SmartParkUserCardVO> result = new ArrayList<>();
        //查询卡号
        SmartParkCardExample smartParkCardExample = new SmartParkCardExample();
        SmartParkCardExample.Criteria cardExampleCriteria = smartParkCardExample.createCriteria();
        cardExampleCriteria.andTenantIdEqualTo(vo.getTenantId());
        cardExampleCriteria.andStatusEqualTo(1);
        cardExampleCriteria.andIsDeletedEqualTo(0);
        smartParkCardExample.setOrderByClause("gmt_create desc");
        //暂时没有做访客卡  先注释调
        //cardExampleCriteria.andUserTypeEqualTo(1);
        List<SmartParkCard> smartParkCards = smartParkCardMapper.selectByExample(smartParkCardExample);
        if (StringUtils.isEmpty(smartParkCards)) {
            return ResponseBodyWrapperUtil.fail("卡数据为空","400");
        }
        for(SmartParkCard card : smartParkCards){
            if(!smartParkDeviceAuthService.authUserIdandDeviceCode(deviceCode,Convert.toStr(card.getUserId()),vo.getOrgCode(),vo.getTenantId())){
                continue;
            }
            //查询员工凭证
            SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
            SmartParkUserConfigExample.Criteria criteria = smartParkUserConfigExample.createCriteria();
            criteria.andIsDeletedEqualTo(0);
            criteria.andTenantIdEqualTo(vo.getTenantId());
            criteria.andAccessStartDateLessThanOrEqualTo(new Date());
            criteria.andAccessEndDateGreaterThanOrEqualTo(new Date());
            criteria.andUserIdEqualTo(card.getUserId());
            List<SmartParkUserConfig> passRecords = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
            if (StringUtils.isEmpty(passRecords)) {
                continue;
            }
            SmartParkUserConfig smartParkUserConfig = passRecords.get(0);
            if(StringUtils.isNull(smartParkUserConfig)){
                continue;
            }
            if(smartParkUserConfig.getBeAccessCard()==0){
                continue;
            }
            //装载数据
            SmartParkUserCardVO smartParkUserCardVO = new SmartParkUserCardVO();
            smartParkUserCardVO.setUserId(smartParkUserConfig.getUserId());
            smartParkUserCardVO.setUserType(1);
            smartParkUserCardVO.setPhoneNum(smartParkUserConfig.getPhoneNum());
            smartParkUserCardVO.setUserName(smartParkUserConfig.getName());
            if (smartParkUserConfig.getAccessDateType() == 1) {
                smartParkUserCardVO.setAccessStartDate(smartParkUserConfig.getAccessStartDate());
                smartParkUserCardVO.setAccessEndDate(smartParkUserConfig.getAccessEndDate());
            }
            smartParkUserCardVO.setGmtModified(smartParkUserConfig.getGmtModified() == null ? smartParkUserConfig.getGmtCreate() : smartParkUserConfig.getGmtModified());
            smartParkUserCardVO.setCardNum(card.getCardNum());
            result.add(smartParkUserCardVO);
        }
        //查询员工，装载数据
        return ResponseBodyWrapperUtil.successWrapper(result);
    }

    /**
     * 查询用户凭证列表
     *
     * @param vo 用户凭证
     * @return 用户凭证
     */
    @Override
    public CommonResponseBody<SmartParkUserCardVO> selectUserCardDetailListByCard(DevicePullDataVo vo) throws Exception {
        String deviceCode = vo.getDeviceCode();
        String cardNum = vo.getCardNum();
        if(StringUtils.isEmpty(deviceCode)){
            return ResponseBodyWrapperUtil.fail("设备code为空","400");
        }
        if(StringUtils.isEmpty(cardNum)){
            return ResponseBodyWrapperUtil.fail("卡号为空","400");
        }
        //查询卡号
        SmartParkCardExample smartParkCardExample = new SmartParkCardExample();
        SmartParkCardExample.Criteria cardExampleCriteria = smartParkCardExample.createCriteria();
        cardExampleCriteria.andTenantIdEqualTo(vo.getTenantId());
        cardExampleCriteria.andCardNumEqualTo(cardNum);
        cardExampleCriteria.andStatusEqualTo(1);
        cardExampleCriteria.andIsDeletedEqualTo(0);
        smartParkCardExample.setOrderByClause("gmt_create desc");
        List<SmartParkCard> smartParkCards = smartParkCardMapper.selectByExample(smartParkCardExample);
        if(StringUtils.isEmpty(smartParkCards)){
            return ResponseBodyWrapperUtil.fail("无效卡","400");
        }
        SmartParkCard smartParkCard = smartParkCards.get(0);
        //根据设备code查询所有绑定人
        if(!smartParkDeviceAuthService.authUserIdandDeviceCode(deviceCode,Convert.toStr(smartParkCard.getUserId()),vo.getOrgCode(),vo.getTenantId())){
            return ResponseBodyWrapperUtil.fail("无设备权限","400");
        }
        SmartParkUserCardVO smartParkUserCardVO = new SmartParkUserCardVO();
        smartParkUserCardVO.setCardNum(cardNum);
        //查询员工凭证
        SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
        SmartParkUserConfigExample.Criteria criteria = smartParkUserConfigExample.createCriteria();
        criteria.andIsDeletedEqualTo(0);
        criteria.andAccessStartDateLessThanOrEqualTo(new Date());
        criteria.andAccessEndDateGreaterThanOrEqualTo(new Date());
        criteria.andUserIdEqualTo(Convert.toLong(smartParkCard.getUserId()));
        List<SmartParkUserConfig> passRecords = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
        if(StringUtils.isEmpty(passRecords)){
            return ResponseBodyWrapperUtil.fail("无效卡","400");
        }
        //装载数据
        SmartParkUserConfig smartParkUserConfig = passRecords.get(0);
        if(smartParkUserConfig.getBeAccessCard()==0){
            return ResponseBodyWrapperUtil.fail("无效卡","400");
        }
        smartParkUserCardVO.setUserId(smartParkUserConfig.getUserId());
        smartParkUserCardVO.setUserType(1);
        smartParkUserCardVO.setPhoneNum(smartParkUserConfig.getPhoneNum());
        smartParkUserCardVO.setUserName(smartParkUserConfig.getName());
        if(smartParkUserConfig.getAccessDateType()==1) {
            smartParkUserCardVO.setAccessStartDate(smartParkUserConfig.getAccessStartDate());
            smartParkUserCardVO.setAccessEndDate(smartParkUserConfig.getAccessEndDate());
        }
        smartParkUserCardVO.setGmtModified(smartParkUserConfig.getGmtModified()==null?smartParkUserConfig.getGmtCreate():smartParkUserConfig.getGmtModified());
        //访客 暂时不做卡
        return ResponseBodyWrapperUtil.successWrapper(smartParkUserCardVO);
    }

    /**
     * 查询用户凭证列表
     * 
     * @param qo 用户凭证
     * @return 用户凭证
     */
    @Override
    public CommonResponseBody<List<SmartParkUserConfigVO>> selectSmartParkUserConfigList(SmartParkUserConfigQO qo)
    {
        SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
        SmartParkUserConfigExample.Criteria criteria = smartParkUserConfigExample.createCriteria();
        if (qo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        if (qo.getBeAuthorization() != null) {
            criteria.andBeAuthorizationEqualTo(qo.getBeAuthorization());
        }
        if (qo.getBeAccessCard() != null) {
            criteria.andBeAccessCardEqualTo(qo.getBeAccessCard());
        }
        if (qo.getBeQrCode() != null) {
            criteria.andBeQrCodeEqualTo(qo.getBeQrCode());
        }
        if (qo.getBeAccessCar() != null) {
            criteria.andBeAccessCarEqualTo(qo.getBeAccessCar());
        }
        if (qo.getSerachText() != null) {
            smartParkUserConfigExample.setSerachText(qo.getSerachText());
        }
        if (qo.getEmploy() != null) {
            criteria.andEmployLike("%"+qo.getEmploy()+"%");
        }
        criteria.andIsDeletedEqualTo(0);
        if (qo.getNeedPage()) {
            smartParkUserConfigExample.setOrderByClause("gmt_create desc limit " + (qo.getPageIndex() - 1) * qo.getPageSize() + "," + qo.getPageSize());
        } else {
            smartParkUserConfigExample.setOrderByClause("gmt_create desc");
        }
        List<SmartParkUserConfig> passRecords = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
        long count = smartParkUserConfigMapper.countByExample(smartParkUserConfigExample);
        return ResponseBodyWrapperUtil
                .successListWrapper(passRecords, count, qo, SmartParkUserConfigVO.class);
    }

    /**
     * 新增用户凭证
     * 
     * @param vo 用户凭证
     * @return 结果
     */
    @Override
    public CommonResponseBody<Boolean> insertSmartParkUserConfig(@Valid SmartParkUserConfigVO vo) throws Exception {
        // 验证 todo
        SmartParkUserConfigExample smartParkUserConfigExample = new SmartParkUserConfigExample();
        SmartParkUserConfigExample.Criteria criteria = smartParkUserConfigExample.createCriteria();
        if (vo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(vo.getTenantId());
        }
        criteria.andIsDeletedEqualTo(0);
        criteria.andUserIdEqualTo(Convert.toLong(vo.getUserId()));
        List<SmartParkUserConfig> passRecords = smartParkUserConfigMapper.selectByExample(smartParkUserConfigExample);
        if(StringUtils.isEmpty(passRecords)){
            return ResponseBodyWrapperUtil.fail("用户凭证已存在","400");
        }
        SmartParkUserConfig smartParkUserConfig = new SmartParkUserConfig();
        try {
            BeanUtil.insertConversion(vo, smartParkUserConfig);
        } catch (Exception e) {
            logger.error("", e);
        }
        smartParkUserConfig.beforeInsert();
        if(StringUtils.isNotEmpty(smartParkUserConfig.getPhoto())){
            SysFileQO sysFileQO = new SysFileQO();
            sysFileQO.setId(Convert.toLong(smartParkUserConfig.getPhoto()));
            sysFileQO.setNeedPage(false);
            CommonResponseBody<SysFileDTO> dtoCommonResponseBody = aclFileRpcService.selectSysFile(sysFileQO);
            if(!dtoCommonResponseBody.isSuccess()){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }

            SysFileDTO sysFileDTO = dtoCommonResponseBody.getData();
            if(StringUtils.isNull(sysFileDTO)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            InputStream inputStream = minioUtil.getObject(sysFileDTO.getBucketName(),sysFileDTO.getFilePath());
            if(StringUtils.isNull(inputStream)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            byte[] photoBt = IoUtil.readBytes(inputStream);
            if(StringUtils.isNull(photoBt)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            byte[] characteristic = faceEngineService.extractFaceFeature(photoBt);
            if(StringUtils.isNull(characteristic)){
                return ResponseBodyWrapperUtil.fail("未识别到人脸信息，请重试","400");
            }
            String filename = IdUtil.objectId()+".data";
            SysFileDTO characteristicFile = new SysFileDTO();
            FileUploadResponse characteristicUploadResponse = minioUtil.uploadFile(characteristic,"user-characteristic",filename);
            if(StringUtils.isNull(characteristicUploadResponse)){
                return ResponseBodyWrapperUtil.fail("未识别到人脸信息，请重试","400");
            }
            characteristicFile.setBusiType(3);
            characteristicFile.setFilePath(filename);
            characteristicFile.setFileName(filename);
            characteristicFile.setFileUrl(characteristicUploadResponse.getUrlHttp());
            characteristicFile.setFileExt("data");
            characteristicFile.setTenantId(vo.getTenantId());
            characteristicFile.setBucketName("user-characteristic");
            CommonResponseBody<SysFileDTO> dtoCommonResponseBody1 = aclFileRpcService.insertSysFile(characteristicFile);
            if(!dtoCommonResponseBody1.isSuccess()){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }

            SysFileDTO sysFileDTO1 = dtoCommonResponseBody1.getData();
            if(StringUtils.isNull(sysFileDTO1)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            smartParkUserConfig.setCharacteristic(Convert.toStr(sysFileDTO1.getId()));
        }

        return ResponseBodyWrapperUtil.toResData(smartParkUserConfigMapper.insertSelective(smartParkUserConfig));
    }

    /**
     * 修改用户凭证
     * 
     * @param vo 用户凭证
     * @return 结果
     */
    @Override
    public CommonResponseBody<Boolean> updateSmartParkUserConfig(@Valid SmartParkUserConfigVO vo) throws Exception {
        // 验证 todo
        SmartParkUserConfig smartParkUserConfig = new SmartParkUserConfig();
        try {
            BeanUtil.insertConversion(vo, smartParkUserConfig);
        } catch (Exception e) {
            logger.error("", e);
        }
        smartParkUserConfig.beforeUpdate();
        if(StringUtils.isNotEmpty(smartParkUserConfig.getPhoto())){
            SysFileQO sysFileQO = new SysFileQO();
            sysFileQO.setNeedPage(false);
            sysFileQO.setId(Convert.toLong(smartParkUserConfig.getPhoto()));
            CommonResponseBody<SysFileDTO> dtoCommonResponseBody = aclFileRpcService.selectSysFile(sysFileQO);
            if(!dtoCommonResponseBody.isSuccess()){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }

            SysFileDTO sysFileDTO = dtoCommonResponseBody.getData();
            if(StringUtils.isNull(sysFileDTO)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            InputStream inputStream = minioUtil.getObject(sysFileDTO.getBucketName(),sysFileDTO.getFilePath());
            if(StringUtils.isNull(inputStream)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            byte[] photoBt = IoUtil.readBytes(inputStream);
            if(StringUtils.isNull(photoBt)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            byte[] characteristic = faceEngineService.extractFaceFeature(photoBt);
            if(StringUtils.isNull(characteristic)){
                return ResponseBodyWrapperUtil.fail("未识别到人脸信息，请重试","400");
            }
            String filename = IdUtil.objectId()+".data";
            SysFileDTO characteristicFile = new SysFileDTO();
            FileUploadResponse characteristicUploadResponse = minioUtil.uploadFile(characteristic,"user-characteristic",filename);
            if(StringUtils.isNull(characteristicUploadResponse)){
                return ResponseBodyWrapperUtil.fail("未识别到人脸信息，请重试","400");
            }
            characteristicFile.setBusiType(3);
            characteristicFile.setFilePath(filename);
            characteristicFile.setFileName(filename);
            characteristicFile.setFileUrl(characteristicUploadResponse.getUrlHttp());
            characteristicFile.setFileExt("data");
            characteristicFile.setTenantId(vo.getTenantId());
            characteristicFile.setBucketName("user-characteristic");
            CommonResponseBody<SysFileDTO> dtoCommonResponseBody1 = aclFileRpcService.insertSysFile(characteristicFile);
            if(!dtoCommonResponseBody1.isSuccess()){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }

            SysFileDTO sysFileDTO1 = dtoCommonResponseBody1.getData();
            if(StringUtils.isNull(sysFileDTO1)){
                return ResponseBodyWrapperUtil.fail("文件获取失败","400");
            }
            smartParkUserConfig.setCharacteristic(Convert.toStr(sysFileDTO1.getId()));
        }
        String userId = null;
        if(StringUtils.isNotNull(smartParkUserConfig.getId())){
            Long[] ids = {smartParkUserConfig.getId()};
            smartParkUserConfig.setIds(ids);
            smartParkUserConfig.setUserId(null);
            userId = Convert.toStr(smartParkUserConfigMapper.selectByPrimaryKey(smartParkUserConfig.getId()).getUserId());
        }

        if(StringUtils.isNotNull(smartParkUserConfig.getUserId())){
            smartParkUserConfig.setIds(null);
            userId = Convert.toStr(smartParkUserConfig.getUserId());
        }
        if(smartParkUserConfig.getAccessDateType()!=null && smartParkUserConfig.getAccessDateType()==1){
            smartParkUserConfig.setAccessStartDate(DateUtil.beginOfDay(smartParkUserConfig.getAccessStartDate()));
            smartParkUserConfig.setAccessEndDate(DateUtil.parse(DateUtil.format(smartParkUserConfig.getAccessEndDate(), "yyyy-MM-dd")+" 23:59:59"));
        }else {
            smartParkUserConfig.setAccessStartDate(DateUtil.beginOfDay(new Date()));
            smartParkUserConfig.setAccessEndDate(DateUtil.parseDateTime("2099-12-31 23:59:59"));
        }

        smartParkUserConfigMapper.updateByPrimaryKeySelective(smartParkUserConfig);

        //判断是否有效期
        boolean isDate = DateUtil.isIn(new Date(),smartParkUserConfig.getAccessStartDate(),smartParkUserConfig.getAccessEndDate());
        // 下发人脸数据
        if(StringUtils.isNull(smartParkUserConfig.getBeAuthorization()) || smartParkUserConfig.getBeAuthorization()==0 || !isDate){
            smartParkDeviceAuthService.sendUserDeviceDelAuth(userId,MqttOptType.DELUSERFACE.getOptCode(),null);
        }else if(smartParkUserConfig.getBeAuthorization()==1 && isDate){
            smartParkDeviceAuthService.sendUserDeviceAuth(userId,MqttOptType.UPDATEUSERFACE.getOptCode(),null);
        }

        //下发卡数据
        if(StringUtils.isNull(smartParkUserConfig.getBeAccessCard()) || smartParkUserConfig.getBeAccessCard()==0  || !isDate){
            smartParkDeviceAuthService.sendUserDeviceDelAuthBatch(userId,MqttOptType.DELUSERCARD.getOptCode(),smartParkUserConfig.getTenantId());
        }else if(smartParkUserConfig.getBeAuthorization()==1 && isDate){
            smartParkDeviceAuthService.sendUserDeviceAuthBatch(userId,MqttOptType.ADDUSERCARD.getOptCode());
        }

        //下发车牌数据
        if(StringUtils.isNull(smartParkUserConfig.getBeAccessCar()) || smartParkUserConfig.getBeAccessCar()==0  || !isDate){
            smartParkDeviceAuthService.sendUserDeviceDelAuthBatch(userId,MqttOptType.DELUSERCAR.getOptCode(),smartParkUserConfig.getTenantId());
        }else if(smartParkUserConfig.getBeAuthorization()==1 && isDate){
            smartParkDeviceAuthService.sendUserDeviceAuthBatch(userId,MqttOptType.ADDUSERCAR.getOptCode());
        }
        return ResponseBodyWrapperUtil.success();
    }

    /**
     * 删除用户凭证信息
     * 
     * @param vo 用户凭证
     * @return 结果08
     */
    @Override
    public CommonResponseBody<Boolean> deleteSmartParkUserConfig(@Valid SmartParkUserConfigVO vo)
    {
        // 验证 vo
        if(StringUtils.isNotEmpty(vo.getIds())){
            if(vo.getIds().split(",").length<=0){
                return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
            }
        }else {
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkUserConfig smartParkUserConfig = new SmartParkUserConfig();
        try {
            BeanUtil.insertConversion(vo, smartParkUserConfig);
        } catch (Exception e) {
            logger.error("", e);
        }
        smartParkUserConfig.beforeDelete();
        smartParkUserConfig.setIds(Convert.toLongArray(vo.getIds()));
        return ResponseBodyWrapperUtil.toResData(smartParkUserConfigMapper.updateByPrimaryKeySelective(smartParkUserConfig));
    }
}
